package com.ruoyi.management_controller.userinfo.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.BlackListException;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.management_controller.userinfo.domain.UserVo;
import com.ruoyi.management_controller.userinfo.interceptor.JWTUtils;
import com.ruoyi.system.service.ISysUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import com.ruoyi.management_controller.userinfo.mapper.UserinfoMapper;
import com.ruoyi.management_controller.userinfo.domain.Userinfo;
import com.ruoyi.management_controller.userinfo.service.IUserinfoService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.ruoyi.common.utils.MD5Util.getMD5String;

/**
 * 用户信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-07-12
 */
@Service
public class UserinfoServiceImpl implements IUserinfoService 
{
    @Autowired
    private UserinfoMapper userinfoMapper;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询用户信息
     * 
     * @param id 用户信息主键
     * @return 用户信息
     */
    @Override
    public Userinfo selectUserinfoById(Long id)
    {
        return userinfoMapper.selectUserinfoById(id);
    }

    @Override
    public Userinfo findByPhoneOrUsername(String phone,String username) {
        return userinfoMapper.findByPhoneOrUsername(phone,username);
    }

    @Override
    public Userinfo findByPhoneAndUsername(String phone,String username) {
        return userinfoMapper.findByPhoneAndUsername(phone,username);
    }

    /**
     * 查询用户信息列表
     * 
     * @param userinfo 用户信息
     * @return 用户信息
     */
    @Override
    public List<Userinfo> selectUserinfoList(Userinfo userinfo)
    {
        return userinfoMapper.selectUserinfoList(userinfo);
    }

    /**
     * 新增用户信息
     * 
     * @param userinfo 用户信息
     * @return 结果
     */
    @Override
    public int insertUserinfo(Userinfo userinfo)
    {
        userinfo.setRawPassword(userinfo.getPassword());
        userinfo.setPassword(getMD5String(userinfo.getPassword()));
        userinfo.setCreatedAt(DateUtils.getNowDate());
        if(null==userinfo.getRole()){
            userinfo.setRole(1);
        }
        return userinfoMapper.insertUserinfo(userinfo);
    }

    /**
     * 修改用户信息
     * 
     * @param userinfo 用户信息
     * @return 结果
     */
    @Override
    public int updateUserinfo(Userinfo userinfo)
    {
        userinfo.setPassword(getMD5String(userinfo.getRawPassword()));
        userinfo.setCreatedAt(DateUtils.getNowDate());
        return userinfoMapper.updateUserinfo(userinfo);
    }

    @Override
    public int updatePwd(Userinfo userinfo) {
        return userinfoMapper.updatePwd(userinfo);
    }

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public AjaxResult login(HttpServletResponse response, String username, String password)
    {
        // 登录前置校验
        loginPreCheck(username, password);
        // 验证账号密码

        Userinfo user = userinfoMapper.findByPhoneOrUsername(username,username);
        if(null == user) {
            return AjaxResult.error("用户名或密码不正确");
        }
        if (!getMD5String(password).equals(user.getPassword())){
            return AjaxResult.error("用户名或密码不正确");
        }
        //生成token
        Map<String, String> map = new HashMap<>();
        map.put("userId", String.valueOf(user.getId()));
        map.put("userName", user.getUsername());
        String token = JWTUtils.getToken(map);
        response.setHeader(JWTUtils.USER_LOGIN_TOKEN,token);
        UserVo vo=UserVo.builder().token(token).username(username)
                .parentId(user.getParentId()).id(user.getId())
                .role(user.getRole()).addr(user.getAddr()).
                 phone(user.getPhone()).name(user.getName()).build();
       return AjaxResult.success(vo);
    }


    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
//        // 密码如果不在指定范围内 错误
//        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
//                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
//        {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
//            throw new UserPasswordNotMatchException();
//        }
//        // 用户名不在指定范围内 错误
//        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
//                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
//        {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
//            throw new UserPasswordNotMatchException();
//        }
    }



    /**
     * 批量删除用户信息
     * 
     * @param ids 需要删除的用户信息主键
     * @return 结果
     */
    @Override
    public int deleteUserinfoByIds(Long[] ids)
    {
        return userinfoMapper.deleteUserinfoByIds(ids);
    }

    /**
     * 删除用户信息信息
     * 
     * @param id 用户信息主键
     * @return 结果
     */
    @Override
    public int deleteUserinfoById(Long id)
    {
        return userinfoMapper.deleteUserinfoById(id);
    }
}
